<template>
  <div class="edit-post-page container w-690 mb-4">
    <h4>编辑文章</h4>
    <uploader
      v-if="isShow"
      action="/upload"
      :uploadFile="uploadFile"
      :class="uploaderClass"
      :beforeUpload="beforeUpload"
      @file-upload-success="handleFileUploaded"
      @file-upload-error="handleFileUploadError"
      @file-upload-delete="handleFileUploadDelete"
    >
      <template #default>
        <h4>上传头图</h4>
      </template>
      <template #loading>
        <div class="d-flex">
          <div class="spinner-border text-secondary">
            <span class="visually-hidden">Loading...</span>
          </div>
        </div>
      </template>
      <template #success="{ resp }">
        <img :src="resp.data.url" :alt="resp.data._id" />
      </template>
      <template #error>
        <h4>上传失败</h4>
      </template>
    </uploader>
    <validate-form @form-submit="onFormSubmit">
      <div class="mb-3">
        <label class="form-label">文章标题：</label>
        <validate-input
          type="text"
          :rules="titleRules"
          v-model="titleVal"
          placeholder="请输入文章标题"
        ></validate-input>
      </div>
      <div class="mb-3">
        <label class="form-label">文章详情：</label>
        <validate-input
          rows="10"
          tag="textarea"
          :rules="contentRules"
          v-model="contentVal"
          placeholder="请输入文章详情"
        ></validate-input>
      </div>
      <template #submit>
        <button class="btn btn-primary">更新文章</button>
      </template>
    </validate-form>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import Uploader from '../components/Uploader.vue'
import { beforeUploadCheck } from '../helper'
import createMessage from '../components/createMessage'
import { ResponseType, ImageProps, GlobalDataProps, PostProps } from '../store'
import ValidateForm from '../components/ValidateForm.vue'
import { useStore } from 'vuex'
import ValidateInput, { RulesProp } from '../components/ValidateInput.vue'
import axios from '../libs/axios'

const uploaderClass = [
  'd-flex',
  'align-items-center',
  'justify-content-center',
  'bg-light',
  'text-secondary',
  'w-100',
  'my-4'
]

interface PostEdit {
  title: string;
  content: string;
  image?: string;
}

export default defineComponent({
  components: {
    Uploader,
    ValidateForm,
    ValidateInput
  },
  setup () {
    const store = useStore<GlobalDataProps>()
    const router = useRouter()
    const route = useRoute()
    const postId = route.params.id

    const isShow = ref(false)
    const uploadFile = ref<null | Record<string, unknown>>(null)

    if (postId) {
      axios({
        url: `/posts/${postId}`,
        method: 'get'
      }).then((res) => {
        const rawData: ResponseType<PostProps> = res.data
        if (rawData.data && rawData.data.image) {
          isShow.value = true
          uploadFile.value = {
            data: rawData.data.image
          }
          imageId = rawData.data.image._id || ''
        }
        titleVal.value = rawData.data.title
        contentVal.value = rawData.data.content
      })
    }

    let imageId = ''

    const titleVal = ref('')

    const contentVal = ref('')

    const titleRules: RulesProp = [
      {
        type: 'required',
        message: '文章标题不能为空'
      }
    ]

    const contentRules: RulesProp = [
      {
        type: 'required',
        message: '文章详情不能为空'
      }
    ]

    const beforeUpload = (file: File): boolean => {
      const result = beforeUploadCheck(file, {
        format: ['image/jpeg', 'image/png'],
        size: 1
      })
      const { isPass, error } = result
      if (error === 'format') {
        createMessage('error', '上传图片只能是 JPG/PNG 格式', 2000)
      }
      if (error === 'size') {
        createMessage('error', '上传图片大小不能超过 1MB', 2000)
      }
      return isPass
    }

    const handleFileUploaded = (rawData: ResponseType<ImageProps>) => {
      imageId = rawData.data._id || ''
    }

    const handleFileUploadError = () => {
      imageId = ''
    }

    const handleFileUploadDelete = () => {
      imageId = ''
    }

    const onFormSubmit = (result: boolean) => {
      if (result) {
        const { column } = store.state.user
        if (column) {
          const data: PostEdit = {
            title: titleVal.value,
            content: contentVal.value
          }
          if (imageId) {
            data.image = imageId
          }
          axios({
            url: `/posts/${postId}`,
            data,
            method: 'patch'
          }).then((res) => {
            const rawData: ResponseType<PostProps> = res.data
            if (rawData.code === 0) {
              createMessage('success', '编辑成功，2秒后跳转至个人专栏', 2000)
              setTimeout(() => {
                router.replace({
                  name: 'column',
                  params: {
                    id: column
                  }
                })
              }, 2000)
            }
          })
        }
      }
    }

    return {
      uploaderClass,
      beforeUpload,
      handleFileUploaded,
      onFormSubmit,
      titleVal,
      contentVal,
      titleRules,
      contentRules,
      isShow,
      uploadFile,
      handleFileUploadError,
      handleFileUploadDelete
    }
  }
})
</script>

<style scoped>
.w-690 {
  width: 690px;
  margin: 0 auto;
}
</style>

<style>
.edit-post-page .uploader-container .uploader {
  height: 200px;
  cursor: pointer;
  position: relative;
}
.edit-post-page .uploader-container .uploader img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.edit-post-page .uploader-container .uploader .deleter-container {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: rgba(0, 0, 0, 0.6);
  opacity: 0;
  display: flex;
  justify-content: center;
  align-items: center;
}
.edit-post-page .uploader-container .uploader .deleter-container:hover {
  opacity: 1;
}
</style>
